package com.wanmait.community.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.community.entity.Device;
import com.wanmait.community.mapper.DeviceInboundPicMapper;
import com.wanmait.community.mapper.DeviceMapper;
import com.wanmait.community.mapper.InboundPicMapper;
import com.wanmait.community.service.DeviceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService{
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private InboundPicMapper inboundPicMapper;
    @Resource
    private DeviceInboundPicMapper deviceInboundPicMapper;
    @Override
    public PageInfo<Device> findAll(Device object, int pageNum, int pageSize) {
        /*该方法为实现前端只给一个yyyy-MM-dd格式的时间,但是数据库的时间格式是yyyy-MM-dd HH:mm:ss，为了能够查到当天内所有的device对象，
        需要指定一个起始时间即0点，结束时间23:59:59的时间范围，而起始时间为前端form提交的时间，已经是0点，那么yyyy-MM-dd 23:59:59的yyyy-MM-dd部分
        就要从object里取，23:59:59为自定义，该方法为ai生成*/
        PageHelper.startPage(pageNum, pageSize);
        Date endCreatTime = null;
        Date endUpdateTime = null;
        // 处理 creatTime
        if (object.getCreatTime() != null) {
            endCreatTime = Date.from(
                    object.getCreatTime().toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDateTime()
                            .withHour(23).withMinute(59).withSecond(59)
                            .atZone(ZoneId.systemDefault())
                            .toInstant()
            );
        }
        // 处理 updateTime
        if (object.getUpdateTime() != null) {
            endUpdateTime = Date.from(
                    object.getUpdateTime().toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDateTime()
                            .withHour(23).withMinute(59).withSecond(59)
                            .atZone(ZoneId.systemDefault())
                            .toInstant()
            );
        }
        List<Device> devices = deviceMapper.selectDevicePageInfo(object, endCreatTime, endUpdateTime);
        // 3. 遍历设备列表，检查是否过期
        // 使用同一时区创建当前时间
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai")); // 根据您实际时区调整
        Date currentDate = cal.getTime();
        for (Device device : devices) {//遍历当前页码下所有device对象
            if (device.getStartTime() != null && device.getServiceLife() != null) {
                // 计算 startTime + serviceLife 的过期时间
                Calendar calendar = Calendar.getInstance();//创建一个日历对象
                calendar.setTime(device.getStartTime());//获取设备首次使用时间
                calendar.add(Calendar.YEAR, device.getServiceLife()); // 加上 serviceLife 年
                Date expireDate = calendar.getTime();//新的日历对象
                // 如果当前时间 > 过期时间，则标记为 "过期"
                if (currentDate.after(expireDate)) {
                    device.setStatus("过期");
                    deviceMapper.updateStatus(device);//如果过期，实时修改数据库的status
                }
                else if (!currentDate.after(expireDate)) {//测试时为了还原status
                    device.setStatus("正常");
                    deviceMapper.updateStatus(device);
                }
            }
        }
        return new PageInfo<>(devices, 7);//navigatePages是页码数字的按钮个数
    }
    @Override
    public Device getKeepStandardById(Integer id) {//根据id查手册,但不只查手册，是根据device的id查device对象的全部属性
        return deviceMapper.getKeepStandardById(id);
    }

    @Override
    public void insertDeviceInfo(Device device) {//添加device
        deviceMapper.insertDeviceInfo(device);//当往device表加除InboundPic对象的字段，回填deviceId
        // 现在device.getId()可以获取到新插入记录的ID
        device.getInboundPic().setDeviceId(device.getId());
        inboundPicMapper.insertInboundPicByDevicePic(device.getInboundPic());
    }
    @Override
    public void updateDeviceInfo(Device device) {
        // 设置当前时间为更新时间,修改原updateTime
        device.setUpdateTime(new Date());
        deviceMapper.updateDeviceInfo(device);
        inboundPicMapper.updateInboundPicByDevicePic(device.getInboundPic());
    }
    @Override
    public void deleteDeviceInfo(Device device) {//逻辑删除，还要把关联表的数据也假删除了
        // 1. 先删除关联的 InboundPic（如果存在）
        if (device.getInboundPic() != null && device.getInboundPic().getId() != null) {
            inboundPicMapper.deleteInboundPicByDevicePic(device.getInboundPic().getId());
        }
        deviceMapper.deleteDeviceInfo(device.getId());//根据device对象的id
        inboundPicMapper.deleteInboundPicByDevicePic(device.getInboundPic().getId());
    }

}

